<template>
  <div class="publicContent">
    <header-title :list="list"></header-title>
    <page-title :name="htmltitle"></page-title>
    <div class="appendnode">
      <el-tabs v-model="activeName" @tab-click="tabchange">
        <el-tab-pane label="我上传的" name="0"></el-tab-pane>
        <el-tab-pane label="待我审批" name="1" v-if="routePath == '/index/gather'"></el-tab-pane>
        <el-tab-pane label="我已审批" name="2" v-if="routePath == '/index/gather'"></el-tab-pane>
      </el-tabs>
      <el-form :model="form" :inline="true" ref="form" label-width="75px" size="small">
        <el-form-item label="文档作者:" v-if="activeName != '0' && routePath == '/index/gather'">
          <el-input v-model="form.author" placeholder="输入要搜索的作者"></el-input>
        </el-form-item>
        <el-form-item label="文档状态:" v-if="activeName == '0' && routePath == '/index/gather'">
          <el-select v-model="form.wordstate" style="width:100%;" placeholder="请选择">
            <el-option label="制定中" :value=0></el-option>
            <el-option label="待审批" :value=1></el-option>
            <el-option label="已发布" :value=2></el-option>
            <el-option label="已驳回" :value=3></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="routePath == '/index/gather'?'文档标题:':'标题:'">
          <el-input v-model="form.title" placeholder="输入标题"></el-input>
        </el-form-item>
        <el-form-item label="审批状态:" v-if="activeName == '2'">
          <el-select v-model="form.state" style="width:100%;">
            <el-option label="请选择" value=""></el-option>
            <el-option label="已发布" value="2"></el-option>
            <el-option label="已驳回" value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发布日期:">
          <el-date-picker
            v-model="form.date"
            type="daterange"
            value-format="yyyy-MM-dd HH:mm:ss"
            :default-time="['00:00:00', '23:59:59']"
            range-separator="~"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('form')">搜索</el-button>
          <el-button @click="resetForm('form')">重置</el-button>
        </el-form-item>
      </el-form>
      <div class="table">
        <div style="display:flex;justify-content:flex-end;padding:0 20px;">
          <el-button @click="showdialog('addnotice')" type="primary" size="small" v-if="routePath != '/index/gather'">新增</el-button>
          <el-button @click="clickupload()" type="success" size="small" v-if="routePath == '/index/gather' && (activeName == '0' || activeName == '2')">上传</el-button>
          <el-button @click="showdialog('shenpiDialog')" type="success" size="small" v-if="activeName == '1'">审批</el-button>
        </div>
        <!-- 表格+分页 -->
        <my-table v-if="routePath == '/index/gather'" :tableData="tableData" :tableTh="tablegatherTh[activeName]" :tableradio="true" :templateRadio="templateRadio" :typeindex="true" :currentPage="currentPage" :pageSize="pageSize" :pageSizes="[15,20,40,80]" :total="total" :layout="'prev, pager, next, total, jumper, sizes'" @getTemplateRow="getTemplateRow" @godetail="godetail" @handleSizeChange="handleSizeChange" @handleCurrentChange="handleCurrentChange" @editknowledge="clickupload"></my-table>
        <my-table v-else :tableData="tableData" :tableTh="tableTh" :tableradio="true" :templateRadio="templateRadio" :typeindex="true" :currentPage="currentPage" :pageSize="pageSize" :pageSizes="[15,20,40,80]" :total="total" :layout="'prev, pager, next, total, jumper, sizes'" @getTemplateRow="getTemplateRow" @godetail="godetail" @handleSizeChange="handleSizeChange" @handleCurrentChange="handleCurrentChange" @edit="showdialog"></my-table>
      </div>
    </div>
    <choose-category :dialog="dialog" @FnDialog="FnDialog"></choose-category>
  </div>
</template>

<script>
import HeaderTitle from '../../components/breadcrumb';
import PageTitle from '../../components/pagetitle';
import ChooseCategory from '../../components/chooseCategory';
import myTable from '@/components/myTable';
export default {
  components:{
    HeaderTitle,
    PageTitle,
    ChooseCategory,
    myTable
  },
  inject: ['reload','user','obj'],
  data () {
    return {
      list:[
        {
          id:'0',
          name:'首页',
          to: '/index/'
        },{
          id:'1',
          name:'知识管理'
        },{
          id:'2',
          name:'知识采编'
        }
      ],
      htmltitle: '知识采编',//页面标题
      activeName: '0',//当前tab,用来判断哪些显示哪些不显示
      form: {
        title: '',//文档标题/标题
        author: '',//文档作者
        date: null,//发布日期
        state: '',//审批状态
        wordstate: '',//文档状态
      },
      tablegatherTh: [
        [
          {
            prop: 'knowledgeName',
            label: '文档标题'
          },
          {
            prop: 'createUser',
            label: '文档作者'
          },
          {
            prop: 'knowledgePublishTime',
            label: '发布日期'
          },
          {
            prop: 'knowledgeStatus',
            label: '文档状态'
          },
          {
            prop: 'knowledgeCategory',
            label: '所属分类'
          },
          {
            type: 'gathercaozuo',
            width:100,
            label: '操作'
          }
        ],
        [
          {
            prop: 'knowledgeName',
            label: '文档标题'
          },
          {
            prop: 'userName',
            label: '文档作者'
          },
          {
            prop: 'knowledgePublishTime',
            label: '发布日期'
          },
          {
            prop: 'categoryName',
            label: '所属分类'
          }
        ],
        [
          {
            prop: 'knowledgeName',
            label: '文档标题'
          },
          {
            prop: 'userName',
            label: '文档作者'
          },
          {
            prop: 'knowledgePublishTime',
            label: '发布日期'
          },
          {
            prop: 'categoryName',
            label: '所属分类'
          },
          {
            prop: 'knowledgeExamineStatus',
            label: '文档状态'
          }
        ],
      ],
      tableTh: [
        {
          prop: 'noticeName',
          label: '公告标题'
        },
        {
          prop: 'userTbl',
          label: '发布人'
        },
        {
          prop: 'noticePublishCreateTime',
          label: '发布日期'
        },
        {
          prop: 'userTbl',
          label: '所属部门'
        },
        {
          type: 'caozuo',
          label: '操作'
        }
      ],
      tableData: [],
      templateRadio: '',//表格单选框
      templateSelection: '',//选中当前行
      currentPage: 1,//当前页
      pageSize: 15,//页大小
      total: 0,//数据总数
      routePath: '',//当前路由，用来判断哪些显示哪些不显示
      // 弹窗数据
      dialog: {
        showDialog: false,
        title: '',
        width: '500px',
        data: {},
      },
      searchData: {},
    }
  },
  watch: {
    /**
     * 监听路由，判断当前页面
     */
    $route (to,from) {
      this.activeName = '0'
      this.currentPage = 1;
      this.pageSize = 15;
      this.total = 0;
      this.resetForm('form');
      this.routePath = this.$route.path
      if (this.routePath == '/index/gather') {
        this.list[1].name = '知识管理'
        this.list[2].name = '知识采编'
        this.htmltitle = '知识采编'
      } else if (this.routePath == '/index/announcement') {
        this.list[1].name = '公告管理'
        this.list[2].name = '公告维护'
        this.htmltitle = '公告维护'
      }
      this.reload()
      this.loadData(this.routePath, this.searchData)
    }
  },
  created() {
    this.routePath = this.$route.path
    this.activeName = '0'
    this.currentPage = 1;
    this.pageSize = 15;
    this.total = 0;
    this.resetForm('form');
    if (this.routePath == '/index/gather') {
      this.list[1].name = '知识管理'
      this.list[2].name = '知识采编'
      this.htmltitle = '知识采编'
    } else if (this.routePath == '/index/announcement') {
      this.list[1].name = '公告管理'
      this.list[2].name = '公告维护'
      this.htmltitle = '公告维护'
    }
    this.loadData(this.routePath, this.searchData)
  },
  methods: {
    // 请求数据,第二个参数是搜索
    loadData(val,data) {
      let _this = this
      if (val == '/index/gather') {
        if (this.activeName == '0') {
          if (JSON.stringify(data) == "{}") {
            data = {
              page: true,
              pageSize: _this.pageSize,
              pages: _this.currentPage,
              userId: _this.user.userId,
            }
          } else {
            data = {...{
              page: true,
              pageSize: _this.pageSize,
              pages: _this.currentPage,
              userId: _this.user.userId,
            },...data}
          }
          this._API.findknowledge(data).then(res=>{
            // console.log(res.data)
            this.tableData = res.data.data.records
            this.total = res.data.data.total
          }).catch(err=>{})
        } else if (this.activeName == '1') {
          if (JSON.stringify(data) == "{}") {
            data = {
              pageSize: _this.pageSize,
              pageNum: _this.currentPage,
              knowledgeExamineStatus: '1',
              userId: _this.user.userId,
            }
          } else {
            data = {...{
              pageSize: _this.pageSize,
              pageNum: _this.currentPage,
              knowledgeExamineStatus: '1',
              userId: _this.user.userId,
            },...data}
          }
          this._API.findapprovalknowledge(data).then(res=>{
            // console.log(res.data)
            this.tableData = res.data.data.list
            this.total = res.data.data.total
          }).catch(err=>{})
        } else if (this.activeName == '2') {
          if (JSON.stringify(data) == "{}") {
            data = {
              pageSize: _this.pageSize,
              pageNum: _this.currentPage,
              knowledgeExamineStatus: '2,3',
              userId: _this.user.userId,
            }
          } else {
            data = {...{
              pageSize: _this.pageSize,
              pageNum: _this.currentPage,
              knowledgeExamineStatus: '2,3',
              userId: _this.user.userId,
            },...data}
          }
          this._API.findapprovalknowledge(data).then(res=>{
            // console.log(res.data)
            this.tableData = res.data.data.list
            this.total = res.data.data.total
          }).catch(err=>{})
        }
      } else if (val == '/index/announcement') {
        if (JSON.stringify(data) == "{}") {
          data = {
            page: true,
            pageSize: _this.pageSize,
            pages: _this.currentPage,
            userId: _this.user.userId,
          }
        } else {
          data = {...{
            page: true,
            pageSize: _this.pageSize,
            pages: _this.currentPage,
            userId: _this.user.userId,
          },...data}
        }
        this._API.findnotice(data)
        .then(res=>{
          // console.log(res.data.data)
          this.tableData = res.data.data.records
          this.total = res.data.data.total
        }).catch(err=>{})
      }
    },
    // 点击选项卡
    tabchange(){
      this.currentPage = 1;
      this.pageSize = 15;
      this.total = 0;
      this.resetForm('form');
      this.templateRadio = ''
      this.templateSelection = ''
      this.tableData = []
      this.loadData(this.routePath, this.searchData)
    },
    // 搜索
    submitForm(formName) {
      if (this.routePath == '/index/announcement') {
        this[formName].title != '' ? this.searchData.title = this[formName].title : delete this.searchData.title
        this[formName].date != null ? (this.searchData.publishStartTime = this[formName].date[0],this.searchData.publishEndTime = this[formName].date[1]) : (delete this.searchData.publishStartTime, delete this.searchData.publishEndTime)
      } else if (this.routePath == '/index/gather')  {
        if (this.activeName == '0') {
          this[formName].title != '' ? this.searchData.title = this[formName].title : delete this.searchData.title
          this[formName].date != null ? (this.searchData.publishStartTime = this[formName].date[0],this.searchData.publishEndTime = this[formName].date[1]) : (delete this.searchData.publishStartTime, delete this.searchData.publishEndTime)
          this[formName].wordstate !== '' ? this.searchData.knowledgeStatus = this[formName].wordstate : delete this.searchData.knowledgeStatus
        } else if (this.activeName == '1') {
          this[formName].author != '' ? this.searchData.knowledgeCreateName = this[formName].author : delete this.searchData.knowledgeCreateName
          this[formName].title != '' ? this.searchData.knowledgeName = this[formName].title : delete this.searchData.knowledgeName
          this[formName].date != null ? (this.searchData.knowledgeCreateStartTime = this[formName].date[0],this.searchData.knowledgeCreateEndTime = this[formName].date[1]) : (delete this.searchData.knowledgeCreateStartTime, delete this.searchData.knowledgeCreateEndTime)
        } else if (this.activeName == '2') {
          this[formName].author != '' ? this.searchData.knowledgeCreateName = this[formName].author : delete this.searchData.knowledgeCreateName
          this[formName].title != '' ? this.searchData.knowledgeName = this[formName].title : delete this.searchData.knowledgeName
          this[formName].date != null ? (this.searchData.knowledgeCreateStartTime = this[formName].date[0],this.searchData.knowledgeCreateEndTime = this[formName].date[1]) : (delete this.searchData.knowledgeCreateStartTime, delete this.searchData.knowledgeCreateEndTime)
          this[formName].state != '' ? this.searchData.knowledgeExamineStatus = this[formName].state : delete this.searchData.knowledgeExamineStatus
        }
      }
      this.currentPage = 1;
      this.total = 0;
      this.loadData(this.routePath, this.searchData)
    },
    // 重置
    resetForm(formName) {
      this[formName] = {
        title: '',
        author: '',
        date: null,
        state: '',
        wordstate: '',
      }
      this.searchData = {}
    },
    // 点击表格单选框
    getTemplateRow(index,row){
      this.templateRadio = index
      this.templateSelection = row;
    },
    // 点击表格某行去详情，除了单选框和操作两列不跳转
    godetail(row, column, cell, event) {
      if (this.routePath == '/index/gather') {
        this.$router.push({
          name: 'details',
          params: {
            knowledgeId: row.knowledgeId
          }
        })
      } else if (this.routePath == '/index/announcement') {
        this.$router.push({
          name: 'noticedetail',
          params: {
            noticeId: row.noticeId
          }
        })
      }
    },
    // 分页选择显示条数
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.currentPage = 1;
      this.total = 0;
      this.loadData(this.routePath, this.searchData)
    },
    // 点击分页
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.currentPage = val;
      this.loadData(this.routePath, this.searchData)
    },
    // 点击上传
    clickupload (row) {
      if (row) {
        this.$router.push({
          name: 'uploadContent',
          params: {
            type: 'edit',
            knowledgeId: row.knowledgeId
          }
        })
      } else {
        this.$router.push({
          name: 'uploadContent',
          params: {
            type: 'addnew',
            knowledgeId: 'auto'
          }
        })
      }
    },
    // 弹窗接收子组件数据
    FnDialog(val) {
        let dialog = this.dialog
        if (val.type == 'submit' && val.data.editnotice) {
          val.data.noticeDetail = val.content
          if (val.data.noticeName == '') {
            this.$message.warning('公告标题不能为空');
            return false;
          }
          if (val.data.noticeType === '') {
            this.$message.warning('请选择接公告分类');
            return false;
          }
          if (val.data.noticeDetail == '') {
            this.$message.warning('公告内容不能为空');
            return false;
          }
          if (val.data.noticeReceiveOrganizationId.join(',') === '') {
            this.$message.warning('请选择接收部门');
            return false;
          }
          dialog.showDialog = false
          val.data.noticeReceiveOrganizationId = val.data.noticeReceiveOrganizationId.join(','),
          delete  val.data.editnotice
          delete  val.data.branchoptions
          this._API.addeditnotice(val.data)
          .then(res=>{
            this.loadData(this.routePath, this.searchData)
          }).catch(err=>{})
        }
        if (val.type == 'submit' && val.data.addnotice) {
          val.data.noticeDetail = val.content
          if (val.data.noticeName == '') {
            this.$message.warning('公告标题不能为空');
            return false;
          }
          if (val.data.noticeType === '') {
            this.$message.warning('请选择接公告分类');
            return false;
          }
          if (val.data.noticeDetail == '') {
            this.$message.warning('公告内容不能为空');
            return false;
          }
          if (val.data.noticeReceiveOrganizationId.join(',') === '') {
            this.$message.warning('请选择接收部门');
            return false;
          }
          dialog.showDialog = false
          val.data.noticeReceiveOrganizationId = val.data.noticeReceiveOrganizationId.join(','),
          delete  val.data.addnotice
          delete  val.data.branchoptions
          delete  val.data.userTbl
          this._API.addeditnotice(val.data)
          .then(res=>{
            this.loadData(this.routePath, this.searchData)
          }).catch(err=>{})
        }
        if (val.type == 'submit' && val.data.shenpiDialog) {
          delete  val.data.shenpiDialog
          delete val.data.knowledgeName
          this._API.approval(val.data).then(res=>{
            this.templateSelection = ''
            this.templateRadio = ''
            this.loadData(this.routePath, this.searchData)
            dialog.showDialog = false
          }).catch(err=>{})
        }
        if (val.type == 'close') {
          dialog.showDialog = false
        }
    },
    // 弹窗展示传递数据
    showdialog (type,val) {
      let _this = this
      let dialog = this.dialog
      
      switch (type) {
        case 'shenpiDialog':
          dialog.showDialog = false
          if (this.templateSelection == '') {
            this.$message({
              message: '请先选中要审批的知识',
              type: 'warning',
              duration: 3000,
            });
          } else {
            dialog.showDialog = true
          }
          dialog.title = '审批'
          dialog.data = {
            shenpiDialog:true,
            knowledgeId: this.templateSelection.knowledgeId,
            knowledgeName: this.templateSelection.knowledgeName,
            knowledgeExamineStatus: '',
            knowledgeExamineOpinion: ''
          }
        break;
        case 'addnotice':
          const loading = this.$loading({
            lock: true,
            text: 'Loading',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          _this._API.getregion().then(res=>{
            // console.log(res.data.obj)
            loading.close();
            dialog.showDialog = true
            dialog.title = '新增公告'
            dialog.width = '660px'
            dialog.data = {
              addnotice:true,
              noticeName: '',
              noticeReceiveOrganizationId: [],
              noticeType: '',
              noticeDetail: '',
              noticePublishUserId: this.user.userId,
              noticePastTime: '',
              userTbl: {
                userName: _this.user.nickName || _this.user.realName ||_this.user.userName,
                region: {
                  regionId: _this.user.userId,
                  regionName: _this.obj.regionName
                }
              },
              branchoptions: [res.data.obj],
            }
          }).catch(err=>{
            loading.close();
          })
        break;
        case 'editnotice':
          const loadings = this.$loading({
            lock: true,
            text: 'Loading',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          _this._API.getregion().then(res=>{
            // console.log(res.data.obj)
            loadings.close();
            dialog.showDialog = true
            let row = val
            dialog.title = '修改公告'
            dialog.width = '660px'
            dialog.data = {
              editnotice:true,
              noticeId: row.noticeId,
              noticeName: row.noticeName,
              noticePublishUserId: row.noticePublishUserId,
              noticeReceiveOrganizationId: row.noticeReceiveOrganizationId.split(','),
              noticeType: row.noticeType,
              noticeDetail: row.noticeDetail,
              noticePublishCreateTime: row.noticePublishCreateTime,
              noticePastTime: row.noticePastTime,
              userTbl: row.userTbl,
              branchoptions: [res.data.obj],
            }
          }).catch(err=>{
            loadings.close();
          })
        break;
      }
    },
  }
}
</script>

<style lang="scss" scoped>
.appendnode /deep/ {
  width: 100%;
  margin-top: 20px;
  .el-tabs__nav-wrap::after {
    background-color: transparent;
  }
  .el-tabs__active-bar {
    background-color: transparent;
  }
}
</style>

